#include "userprofile.h"
#include "filetransfer/downloader.h"
#include "appchat/constantapp.h"
#include "appchat/sqlite/friendprofiletable.h"
#include "../profilemanager.h"

#include <QDir>

UserProfile::UserProfile(QObject *parent) :
    QObject(parent)
  ,_userId(0)
  ,_userName("")
  ,_displayName("")
  ,_avatar("")
  ,_avatarLocal("")
  ,_downloader(NULL)
  ,_online(-1)
  ,_totalMember(1)
  ,_listGroupMember()
{
}


UserProfile::UserProfile(const qint64 userId, const QString& userName, const QString& displayName, const QString& avatar, QObject *parent):
   _userId(userId),
   _userName(userName),
   _displayName(displayName),
   _avatar(avatar),
   _avatarLocal(""),
   _downloader(NULL),
   QObject(parent)
{

}

UserProfile::UserProfile(const UserProfile &uProfile)
    :QObject(),
      _userId(uProfile.getUserId()),
      _userName(uProfile.getUserName()),
      _displayName(uProfile.getDisplayName()),
      _avatar(uProfile.getAvatar())
{
}

void UserProfile::downloadImageAndUpdateLocal()
{
    if(_downloader == NULL){
        _downloader = new FileTransfer::DownLoader();
        connect(_downloader, &FileTransfer::DownLoader::finished,
                this, &UserProfile::onImageDownloaded);

        connect(_downloader, &FileTransfer::DownLoader::progress,
                this, &UserProfile::onDownloadProgress);
    }


    _downloader->download(_avatar, true, PATH_AVATAR_STORE);

}

void UserProfile::updateData2Local()
{
    downloadImageAndUpdateLocal();
}

void UserProfile::onImageDownloaded(const QString &error,
                                           bool aborted,
                                           bool paused)
{
    if (aborted || paused)
        return;

    if (!error.isEmpty())
        return;

    // Store tempFileName
    QString tempFile = _downloader->fileName();
    _avatarLocal = tempFile;


    ProfileManager::instance()->insertProfileThread()->insertFriendProfile(this);
    if (!ProfileManager::instance()->insertProfileThread()->isRunning()) {
        ProfileManager::instance()->insertProfileThread()->start();
    }


    emit updateLocalFinish();

    qDebug() << tempFile;

}


void UserProfile::onDownloadProgress(qint64 received, qint64 total)
{
    if ((total == -1) || (total == 0)) {
//        ui->downloadProgress->hide();
//        return;
    }

//    ui->downloadProgress->show();
//    ui->downloadProgress->setValue((received/total)*100);
}
